<!--
 * Description: PBM报价组件
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/06/1 13:30
-->

<template>
  <div class="fd-quote-edit-pane">
    <!--TODO: 设置用户的习惯按钮 -->
    <el-tooltip class="item" content="自定义表格显示列" effect="dark" placement="top">
      <button class="set-fd-cell" @click="setDialogVisible = true"></button>
    </el-tooltip>
    <div class="custom-top">
      <div class="btn">
        <div class="left">
          <el-link icon="el-icon-folder-checked" @click="saveAll">
            {{ $t('button.submit') }}
          </el-link>
          <el-link icon="el-icon-download" style="margin-left: 15px" @click="rowDown">
            {{ $t('FdData.exportExcel') }}
          </el-link>
          <el-link icon="el-icon-upload2" style="margin-left: 15px" @click="uploadFile">
            {{ $t('FdData.importExcel') }}
          </el-link>
          <input ref="inputfile" class="upload" type="file" @change="inputfileChange" />
        </div>
      </div>
      <div class="total-result">
        <table>
          <tr>
            <td>总行数：{{ totalResult.totalLen }}</td>
            |
            <td>当前行数：{{ totalResult.currentLen }}</td>
            |
            <td>Base Price：{{ totalResult.basePrice }}</td>
            |
            <!-- <td>GCM Cost：{{ totalResult.gcmCost }}</td>
            | -->
            <td>GCM Total Cost Delta：{{ totalResult.gcmTotalCostDelta }}</td>
            |
            <td>PBM Total Cost Delta：{{ totalResult.pbmTotalCostDelta }}</td>
            |
            <td>PBM Commit Total Cost Delta：{{ totalResult.pbmCommitTotalCostDelta }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div v-loading="isRequesting" class="custom-bottom">
      <VirtualTable
        :cb="totalCb"
        cbArgs="basePrice,gcmTotalCostDelta,pbmTotalCostDelta,pbmCommitTotalCostDelta"
        :filterable="true"
        :header-cell-style="$headerCellStyle"
        :rowStyle="rowStyle"
        rowKey="fdRowId"
        :table="shareDataList"
      >
        <!-- rowNo -->
        <Cell fix="left" :label="$t('FdData.rowNo')" :width="50">
          <template slot-scope="scope">
            <span>{{ scope.index + 1 }}</span>
          </template>
        </Cell>
        <!-- basePartName -->
        <Cell
          v-if="cellIsShow.IsFixBasePartName"
          fix="left"
          :label="$t('FdData.basePartName')"
          prop="basePartName"
          sort
          :width="150"
        />
        <!-- basePartNo -->
        <Cell
          v-if="cellIsShow.IsFixBasePartNo"
          fix="left"
          :label="$t('FdData.basePartNo')"
          prop="basePartNo"
          sort
          :width="150"
        />
        <!-- newPartName -->
        <Cell
          v-if="cellIsShow.IsFixNewPartName"
          fix="left"
          :label="$t('FdData.newPartName')"
          prop="newPartName"
          sort
          :width="150"
        />
        <!-- newPartNo -->
        <Cell
          v-if="cellIsShow.IsFixNewPartNo"
          fix="left"
          :label="$t('FdData.newPartNo')"
          prop="newPartNo"
          sort
          :width="150"
        />
        <!-- rdFunction -->
        <Cell
          v-if="cellIsShow.IsRDFunction"
          :label="$t('FdData.rdFunction')"
          prop="rdFunction"
          sort
        />
        <!-- category -->
        <Cell v-if="cellIsShow.IsCategory" :label="$t('FdData.category')" prop="category" sort />
        <!-- itemNo -->
        <Cell v-if="cellIsShow.IsItemNo" :label="$t('FdData.itemNo')" prop="itemNo" sort="number" />
        <!-- rdOwner -->
        <Cell v-if="cellIsShow.IsRDOwner" :label="$t('FdData.rdOwner')" prop="rdOwner" sort />
        <!-- trackingOption -->
        <Cell
          v-if="cellIsShow.IsTrackingOption"
          :label="$t('FdData.trackingOption')"
          prop="trackingOption"
          sort
        />
        <!-- optionType -->
        <Cell v-if="cellIsShow.IsOptionType" :label="$t('FdData.optionType')" prop="optionType" />
        <!-- baseProject -->
        <Cell :label="$t('FdData.baseProject')">
          <!-- basePartName -->
          <Cell
            v-if="cellIsShow.IsBasePartName"
            :label="$t('FdData.basePartName')"
            prop="basePartName"
            sort
            :width="150"
          />
          <!-- basePartNo -->
          <Cell
            v-if="cellIsShow.IsBasePartNo"
            :label="$t('FdData.basePartNo')"
            prop="basePartNo"
            sort
            :width="150"
          />
          <!-- baseMaterialGroup -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialGroup"
            :label="$t('FdData.MaterialGroup')"
            prop="baseMaterialGroup"
            sort
          />
          <!-- baseMaterialDetail -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialDetail"
            :label="$t('FdData.MaterialDetail')"
            prop="baseMaterialDetail"
            sort
          />
          <!-- baseMaterialColor -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialColor"
            :label="$t('FdData.baseMaterialColor')"
            prop="baseMaterialColor"
            sort
          />
          <!-- baseSize -->
          <Cell
            v-if="cellIsShow.IsBaseSize"
            :label="$t('FdData.baseSize')"
            prop="baseSize"
            sort="number"
          />
          <!-- baseQty -->
          <Cell
            v-if="cellIsShow.IsBaseQty"
            :label="$t('FdData.baseQty')"
            prop="baseQty"
            sort="number"
          />
          <!-- baseIdProcess -->
          <Cell
            v-if="cellIsShow.IsBaseIdProcess"
            :label="$t('FdData.baseIdProcess')"
            prop="baseIdProcess"
            sort
          />
          <!-- baseSupplier -->
          <Cell
            v-if="cellIsShow.IsBaseSupplier"
            :label="$t('FdData.baseSupplier')"
            prop="baseSupplier"
            sort
          />
          <!-- baseSupplierPn -->
          <Cell
            v-if="cellIsShow.IsBaseSupplierPn"
            :label="$t('FdData.baseSupplierPn')"
            prop="baseSupplierPn"
            sort
          />
          <!-- baseRemark -->
          <Cell v-if="cellIsShow.IsBaseRemark" :label="$t('FdData.baseRemark')" prop="baseRemark" />
          <!-- baseViewPic -->
          <Cell
            v-if="cellIsShow.IsBaseViewPic"
            :label="$t('FdData.baseViewPic')"
            prop="basePicture"
          >
            <template slot-scope="scope">
              <BaseViewBtn @click="fdPicList(scope.row, false)">
                {{ scope.row.basePicture }}
              </BaseViewBtn>
            </template>
          </Cell>
          <!-- baseSapStandardPrice -->
          <Cell
            v-if="cellIsShow.IsBaseSapStandardPrice"
            :label="$t('FdData.baseSapStandardPrice')"
            prop="baseSapStandardPrice"
            sort="number"
          />
          <!-- basePrice -->
          <Cell
            v-if="cellIsShow.IsBasePrice"
            :label="$t('FdData.basePrice')"
            prop="basePrice"
            sort="number"
          />
          <!-- baseTecCost -->
          <Cell
            v-if="cellIsShow.IsBaseTecCost"
            :label="$t('FdData.baseTecCost')"
            prop="baseTecCost"
            sort="number"
          />
        </Cell>
        <!-- newProject -->
        <Cell :label="$t('FdData.newProject')">
          <!-- newPartName -->
          <Cell
            v-if="cellIsShow.IsNewPartName"
            :label="$t('FdData.newPartName')"
            prop="newPartName"
            sort
            :width="150"
          />
          <!-- newPartNo -->
          <Cell
            v-if="cellIsShow.IsNewPartNo"
            :label="$t('FdData.newPartNo')"
            prop="newPartNo"
            sort
            :width="150"
          />
          <!-- commodity -->
          <Cell
            v-if="cellIsShow.IsNewCommodity"
            :label="$t('FdData.commodity')"
            prop="commodity"
            sort
          />
          <!-- newTempPartNo -->
          <Cell
            v-if="cellIsShow.IsNewTempPartNo"
            :label="$t('FdData.newTempPartNo')"
            prop="newTempPartNo"
            sort
          />
          <!-- newMaterialGroup -->
          <Cell
            v-if="cellIsShow.IsNewMaterialGroup"
            :label="$t('FdData.MaterialGroup')"
            prop="newMaterialGroup"
            sort
          />
          <!-- newMaterialDetail -->
          <Cell
            v-if="cellIsShow.IsNewMaterialDetail"
            :label="$t('FdData.MaterialDetail')"
            prop="newMaterialDetail"
            sort
          />
          <!-- newMaterialColor -->
          <Cell
            v-if="cellIsShow.IsNewMaterialColor"
            :label="$t('FdData.newMaterialColor')"
            prop="newMaterialColor"
            sort
          />
          <!-- newSize -->
          <Cell
            v-if="cellIsShow.IsNewSize"
            :label="$t('FdData.newSize')"
            prop="newSize"
            sort="number"
          />
          <!-- newQty -->
          <Cell
            v-if="cellIsShow.IsNewQty"
            :label="$t('FdData.newQty')"
            prop="newQty"
            sort="number"
          />
          <!-- newIdProcess -->
          <Cell
            v-if="cellIsShow.IsNewIdProcess"
            :label="$t('FdData.newIdProcess')"
            prop="newIdProcess"
            sort
          />
          <!-- newSupplier -->
          <Cell
            v-if="cellIsShow.IsNewSupplier"
            :label="$t('FdData.newSupplier')"
            prop="newSupplier"
            sort
          />
          <!-- newSupplierPn -->
          <Cell
            v-if="cellIsShow.IsNewSupplierPn"
            :label="$t('FdData.newSupplierPn')"
            prop="newSupplierPn"
            sort
          />
          <!-- newTooling -->
          <Cell
            v-if="cellIsShow.IsNewTooling"
            :label="$t('FdData.newTooling')"
            prop="newTooling"
            sort
          >
            <template slot-scope="scope">
              <span>{{ scope.row.newTooling ? 'Y' : 'N' }}</span>
            </template>
          </Cell>
          <!-- newRemark -->
          <Cell v-if="cellIsShow.IsNewRemark" :label="$t('FdData.newRemark')" prop="newRemark" />
          <!-- newViewPic -->
          <Cell v-if="cellIsShow.IsNewViewPic" :label="$t('FdData.newViewPic')" prop="newPicture">
            <template slot-scope="scope">
              <BaseViewBtn @click="fdPicList(scope.row, true)">
                {{ scope.row.newPicture }}
              </BaseViewBtn>
            </template>
          </Cell>
          <!-- newSapStandardPrice -->
          <Cell
            v-if="cellIsShow.IsNewSapStandardPrice"
            :label="$t('FdData.newSapStandardPrice')"
            prop="newSapStandardPrice"
            sort="number"
          />
          <!-- newPrice -->
          <Cell
            v-if="cellIsShow.IsNewPrice"
            :label="$t('FdData.newPrice')"
            prop="newPrice"
            sort="number"
          />
          <!-- newTecCost -->
          <Cell
            v-if="cellIsShow.IsNewTecCost"
            :label="$t('FdData.newTecCost')"
            prop="newTecCost"
            sort="number"
          />
        </Cell>
        <!-- statusCompare -->
        <Cell
          v-if="cellIsShow.IsStatusCompare"
          :label="$t('FdData.statusCompare')"
          prop="statusCompare"
          sort="number"
        />
        <!-- gapType -->
        <Cell
          v-if="cellIsShow.IsGapType"
          :label="$t('FdData.gapType')"
          prop="gapType"
          sort="number"
        />
        <!-- gapReason -->
        <Cell v-if="cellIsShow.IsGapReason" :label="$t('FdData.gapReason')" prop="gapReason" />
        <!-- gcm -->
        <Cell :label="$t('FdData.gcm')">
          <!-- gcmFunction -->
          <Cell
            v-if="cellIsShow.IsGcmFunction"
            :label="$t('FdData.gcmFunction')"
            prop="gcmFunction"
            sort
          />
          <!-- GcmOwner -->
          <Cell v-if="cellIsShow.IsGcmOwner" :label="$t('FdData.gcmOwner')" sort>
            <template slot-scope="scope">
              {{ gcmOwnerById(scope.row.gcmOwner) }}
            </template>
          </Cell>
          <!-- gcmCost -->
          <!-- <Cell
            v-if="cellIsShow.IsGcmCost"
            :label="$t('FdData.gcmCost')"
            prop="gcmCost"
            sort="number"
          /> -->
          <!-- gcmCostDelta -->
          <Cell
            v-if="cellIsShow.IsGcmTotalCostDelta"
            :label="$t('FdData.gcmTotalCostDelta')"
            prop="gcmTotalCostDelta"
            sort="number"
          />

          <!-- gcmCostRemark -->
          <Cell
            v-if="cellIsShow.IsGcmCostRemark"
            :label="$t('FdData.gcmCostRemark')"
            prop="gcmCostRemark"
          />
        </Cell>
        <!-- tecDelta -->
        <!-- <Cell :label="$t('FdData.tecDelta')" prop="tecDelta" sort="number" /> -->
        <!-- aucDelta -->
        <!-- <Cell :label="$t('FdData.aucDelta')" prop="aucDelta" sort="number" /> -->
        <!-- pirDelta -->
        <!-- <Cell :label="$t('FdData.pirDelta')" prop="pirDelta" sort="number" /> -->
        <!-- pbmTotalCostDelta -->
        <Cell :label="$t('FdData.pbmTotalCostDelta')" prop="pbmTotalCostDelta" sort="number" />
        <!-- pbmCommitTotalCostDelta -->
        <Cell
          :label="$t('FdData.pbmCommitTotalCostDelta')"
          prop="pbmCommitTotalCostDelta"
          sort="number"
          :width="200"
        />
        <Cell fix="right" label="操作" :width="220">
          <template slot-scope="scope">
            <el-link :underline="false" @click="rowReferencePrice(scope.index, scope.row)">
              参考价格
            </el-link>
            <el-link
              style="margin-left: 14px"
              :underline="false"
              @click="rowQuote(scope.index, scope.row)"
            >
              报价
            </el-link>
          </template>
        </Cell>
      </VirtualTable>
    </div>

    <!-- 报价对话框 -->
    <BaseDialog
      v-if="quoteDialogVisible"
      :title="$t('button.quote')"
      :visible.sync="quoteDialogVisible"
      width="600px"
    >
      <FdQuoteEdit
        :base-file-data="inputData"
        :current-row-no="currentRowNo"
        :input-data="currentEditRow"
        @cancel="quoteDialogVisible = false"
        @save="afterQuoteSave"
      />
    </BaseDialog>

    <!--图片对话框-->
    <BaseDialog
      v-if="picDialogVisible"
      title="图片查看"
      :visible.sync="picDialogVisible"
      width="400px"
    >
      <BaseIdpPicView
        :idp-token="idpToken"
        :pic-list="picList"
        @cancel="picDialogVisible = false"
      />
    </BaseDialog>
    <!--参考价格-->
    <BaseDialog
      v-if="fdReferencePriceVisible"
      title="参考价格"
      :visible.sync="fdReferencePriceVisible"
      width="700px"
    >
      <FdReferencePrice
        :fdRowId="currentEditRow.fdRowId"
        @cancel="fdReferencePriceVisible = false"
      />
    </BaseDialog>
    <!--TODO: 设置显示列对话框 -->
    <BaseDialog
      v-if="setDialogVisible"
      title="设置显示列"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <FdCellShowSet
        :cellIsShow="cellIsShow"
        :pageId="pageId"
        @cancel="setDialogVisible = false"
        @saveOperationData="saveOperationData"
      />
    </BaseDialog>
  </div>
</template>
<script>
import FdQuoteEdit from './FdQuoteEdit'
import { idpGetToken } from '@/api/quote/idp'
import { fdRowPictureList } from '@/api/quote/fd-row-picture'

import { fdQuoteCommit, fdQuoteSaveBatch } from '@/api/quote/fd'
import { fileExportFdQuote } from '@/api/quote/file-export'
import XLSX from 'xlsx'

import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'

import FdReferencePrice from '../../components/FdReferencePrice.vue'
import fdCell from '@/mixins/fdCell'
import FdCellShowSet from '../../components/FdCellShowSet'

export default {
  name: 'FdQuoteEditPane',
  components: { FdQuoteEdit, VirtualTable, Cell, FdReferencePrice, FdCellShowSet },
  mixins: [fdCell],
  props: {
    inputData: {
      default: () => null,
      type: Object
    },

    shareDataList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 转发对话框可见标识
      quoteDialogVisible: false,
      // 当前修改行
      currentEditRow: {},
      // 当前行号
      currentRowNo: 0,
      // idp token
      idpToken: '',
      // 每一行的图片数据
      picList: [],
      // 图片对话框可见标识
      picDialogVisible: false,
      // 合计信息
      totalResult: {
        totalLen: 0,
        currentLen: 0,
        basePrice: 0,
        gcmCost: 0,
        gcmCostDelta: 0,
        pbmQuote: 0
      },
      // 参考价格显示标识
      fdReferencePriceVisible: false,
      // 正在加载
      isRequesting: false,
      // 未完成的列
      unDoneApproveList: [],
      setDialogVisible: false,
      pageId: 'FdQuoteEditPane',
      cellIsShow: {}
    }
  },
  computed: {
    costDelta() {
      return scope => {
        const pbmCommitQuote = scope.row.pbmCommitQuote
        return pbmCommitQuote
      }
    }
  },
  mounted() {
    this.pageDataInit()
  },
  methods: {
    rowStyle(index, row) {
      if (this.unDoneApproveList.find(item => item.fdRowId === row.fdRowId)) {
        return {
          backgroundColor: '#ffdada'
        }
      }
    },
    pageDataInit(reload) {
      this.getIdpGetToken()
    },

    rowQuote(index, row) {
      this.currentRowNo = index + 1
      this.currentEditRow = this.$deepCopy(row)
      this.quoteDialogVisible = true
    },
    // 全部估价提交
    async saveAll() {
      try {
        await this.$confirmBox(this.$t('button.submit'), 'success')
        this.unDoneApproveList = this.shareDataList.filter(
          item => item.pbmTotalCostDelta === null || item.pbmCommitTotalCostDelta === null
        )
        if (this.unDoneApproveList.length > 0) {
          return this.$message({
            message: '存在未报价数据',
            type: 'error',
            duration: 1500
          })
        }
        this.isRequesting = true

        await fdQuoteCommit(
          { fdId: this.inputData.fdId, version: this.inputData.version },
          { msgSuccess: true, msgError: true }
        )
        this.$emit('cancel')
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    // 报价完成之后
    afterQuoteSave() {
      this.quoteDialogVisible = false
      this.$emit('update')
    },
    async getIdpGetToken() {
      try {
        const idpTokenRes = await idpGetToken({})
        this.idpToken = idpTokenRes.data.accessToken
      } catch (error) {
        console.log(error)
      }
    },
    // 查看fd每一行图片列表
    async fdPicList(data, isNew) {
      const res = await fdRowPictureList({ fdRowId: data.fdRowId, isNew: isNew })
      this.picList = res.data
      this.picDialogVisible = true
    },
    totalCb(args) {
      this.totalResult = { ...args }
    },
    rowReferencePrice(index, row) {
      this.currentEditRow = row
      this.fdReferencePriceVisible = true
    },

    // 下载
    async rowDown() {
      try {
        await this.$confirmBox(this.$t('button.down'), 'success')
        this.isRequesting = true
        const res = await fileExportFdQuote(
          {
            fdId: this.inputData.fdId,
            version: this.inputData.version
          },
          { downExcelFile: true, msgSuccess: true, msgError: true }
        )
        this.$downFile(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    // 上传数据
    uploadFile() {
      this.$refs['inputfile'].click()
    },
    // 读取文件
    inputfileChange(event) {
      const files = event.target.files

      if (!files) return

      const f = files[0]

      const reader = new FileReader()

      reader.onload = async e => {
        const data = e.target.result

        const workbook = XLSX.read(data, { type: 'array' })

        let sheet = workbook.Sheets[workbook.SheetNames[0]]

        // !ref 默认是表格第一行到最后一行(数据的最后一行)

        const maxColumn = sheet['!ref'].split(':')[1]

        sheet['!ref'] = `A2:${maxColumn}`

        // 行是合并单元格需重置

        const A2 = { w: '', t: 's' }
        const B2 = { w: '', t: 's' }
        const C2 = { w: '', t: 's' }
        const D2 = { w: '', t: 's' }
        const E2 = { w: '', t: 's' }
        const F2 = { w: '', t: 's' }

        const AL2 = { w: '', t: 's' }
        const AM2 = { w: '', t: 's' }
        const AN2 = { w: '', t: 's' }

        sheet = { ...sheet, A2, B2, C2, D2, E2, F2, AL2, AM2, AN2 }

        sheet['D2'].w = 'fdRowId'
        sheet['AT2'].w = 'pbmTotalCostDelta'
        sheet['AU2'].w = 'pbmCommitTotalCostDelta'

        const result = XLSX.utils.sheet_to_json(sheet)

        this.saveUploadList(
          // TODO:
          result.map(item => {
            return {
              fdRowId: item.fdRowId || '',
              pbmTotalCostDelta: item.pbmTotalCostDelta || '',
              pbmCommitTotalCostDelta: item.pbmCommitTotalCostDelta || ''
            }
          })
        )

        event.target.value = ''
      }
      reader.readAsArrayBuffer(f)
    },

    // save
    async saveUploadList(list) {
      try {
        this.isRequesting = true

        const uploadList = list.filter(
          item =>
            String(item.pbmTotalCostDelta).trim() !== '' &&
            String(item.pbmCommitTotalCostDelta).trim() !== '' &&
            String(item.fdRowId).trim() !== ''
        )
        await fdQuoteSaveBatch(uploadList, { msgSuccess: true, msgError: true })

        this.$emit('update')
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    }
  }
}
</script>
<style lang="scss">
.fd-quote-edit-pane {
  .custom-top {
    width: calc(100% - 17px);
    height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .btn {
      margin-top: 15px;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .custom-bottom {
    position: absolute;
    top: 80px;
    bottom: 0;
    left: 20px;
    right: 25px;
  }
  .upload {
    width: 0;
    display: none;
  }
}
</style>
